//
//  UIControl+ForbidMultiClick.m
//  runtimeDemo
//
//  Created by admin on 2018/2/8.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "UIControl+ForbidMultiClick.h"
#import <objc/runtime.h>

@implementation UIControl (ForbidMultiClick)

static const char *UIControl_acceptEventInterval = "UIControl_acceptEventInterval";

static const char *UIControl_igonreEvent = "UIControl_ignoreEvent";

+ (void)load {
    Method a = class_getInstanceMethod(self, @selector(sendAction:to:forEvent:));
    Method b = class_getInstanceMethod(self, @selector(custom_sendAction:to:forEvent:));
    method_exchangeImplementations(a, b);
}

- (void)custom_sendAction:(SEL)action to:(id)target forEvent:(UIEvent *)event {
    if ([NSStringFromClass(self.class) isEqualToString:@"_UIButtonBarButton"] || [NSStringFromClass(self.class) isEqualToString:@"UIButton"]) {
        if (self.ignoreEvent)return;
        if (self.acceptEventInterval > 0) {
            self.ignoreEvent = YES;
            [self performSelector:@selector(setIgnoreEvent:) withObject:@(NO) afterDelay:self.acceptEventInterval];
        }
        [self custom_sendAction:action to:target forEvent:event];
    } else {
        [self custom_sendAction:action to:target forEvent:event];
    }
}

- (NSTimeInterval)acceptEventInterval {
    return [objc_getAssociatedObject(self, _cmd) doubleValue] ? [objc_getAssociatedObject(self, _cmd) doubleValue] : 1.0;
}

- (void)setAcceptEventInterval:(NSTimeInterval)acceptEventInterval {
    objc_setAssociatedObject(self, UIControl_acceptEventInterval, [NSNumber numberWithDouble:acceptEventInterval], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

- (BOOL)ignoreEvent {
    return [objc_getAssociatedObject(self, UIControl_igonreEvent) boolValue];
}

- (void)setIgnoreEvent:(BOOL)ignoreEvent {
    return objc_setAssociatedObject(self, UIControl_igonreEvent, [NSNumber numberWithBool:ignoreEvent], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}


@end
